package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.boot.autoconfigure.ssl.SslProperties;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {

    public static WebDriver driver;

    public static String DetailUrl = "http://8.137.19.140:9090/blog_detail.html?blogId=241400";

    public WebDriverWait wait = null;


    public Utils(String url){
        driver = createDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(2));
        driver.get(url);
    }

    public static WebDriver createDriver(){

        if(null == driver){
            System.setProperty("webdriver.edge.driver", "D:/driver/msedgedriver.exe");
            EdgeOptions options = new EdgeOptions();
            // 允许访问所有链接
            options.addArguments("--remote-allow-origins=*");
            driver = new EdgeDriver(options);
            // 隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }

    /**
     * 屏幕截图
     * 目录
     * ./src/test/java/images/
     *                       /2025-10-06/
     *                                  /test01_09372010.png
     *                                  /test01_09372011.png
     *                       /2025-10-07/
     *                                  /test01_19372010.png
     *                                  /test01_19372011.png
     */
    public void ScreenShot(String str) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String fileName = "./src/test/java/images/" + dirTime + "/" + str + "_" + fileTime + ".png";

        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(fileName));
    }
}
